PROJECT = "gnss"
VERSION = "1.0.0"


-- sys库是标配
local lbsLoc = require("lbsLoc")
local lbsLoc2 = require("lbsLoc2")
local sys = require("sys")
require("sysplus")

-- GPS定位失败次数，
local Gps_Get_Num=0
local Gnss_HistoricalNum=0

_G.WIFISearchFlag = false

local Wifi_Num_Max=3
local gps_uart_id = 1
--local gps_uart_id = 2


local lla = {
    lat,
    lng
}


libgnss.clear() -- 清空数据,兼初始化

uart.setup(gps_uart_id, 9600)

function urlEncode(s)
    s = string.gsub(s, "([^%w%.%- ])", function(c)
     return string.format("%%%02X", string.byte(c)) end)
    return string.gsub(s, " ", "+")
end 


function trim(s)
    return (s:gsub("^%s*(.-)%s*$", "%1"))
end

-- 日期时间转时间戳 注意输出格式是xxxx-02-12 09:30:12
-- 参数可以是  “xxxx-02-12 09:30:12” 或者 表{2019,2,12,9,30,12}
function dataToTimeStamp(dataStr)
    local result = -1
    local tempTable = {}

    if dataStr == nil then
        error("传递进来的日期时间参数不合法")
    elseif type(dataStr) == "string" then
        dataStr = trim(dataStr)
        for v in string.gmatch(dataStr, "%d+") do
            tempTable[#tempTable + 1] = v
        end
    elseif type(dataStr) == "table" then
        tempTable = dataStr
    else
        error("传递进来的日期时间参数不合法")
    end

    result = os.time({
        day = tonumber(tempTable[3]),
        month = tonumber(tempTable[2]),
        year = tonumber(tempTable[1]),
        hour = tonumber(tempTable[4]),
        min = tonumber(tempTable[5]),
        sec = tonumber(tempTable[6])
    })
    return result

end

-- Lua equivalent of the random function in C

-- Check if randomSeed was called and use software PRNG if needed
local function random(howbig)
    if howbig == 0 then
        return 0
    end

    if howbig < 0 then
        return random(0, -howbig)
    end

    -- Generate random value using hardware or software PRNG
    local val = (s_useRandomHW) and esp_random() or math.random()
    
    return val % howbig
end

-- Function to generate random number within a range
local function random_range(howsmall, howbig)
    if howsmall >= howbig then
        return howsmall
    end

    local diff = howbig - howsmall
    return random(diff) + howsmall
end



local function getLocCb(result, lat, lng, addr, time, locType)
    -- 获取经纬度成功
    if result == 0 then
        if locType == 0 then

            log.info("------------>基站定位成功",lat,lng)
            _G.data_from="LBS"

        else

            if data_from == "WIFI" then
                _G.data_from = "WIFI"
            else
                _G.data_from = "NoData"
            end

            log.info("------------>基站定位失败",lat,lng)
        end
        
        _G.old_longitude=lng
        _G.old_latitude=lat
        
        -- 发送广播，马上进行数据上报然后休眠--主要针对休眠模式



    else
        log.info("------------>LBS定位失败")
    end

end


sys.taskInit(function()



    -- 打开GPS电源开关
    gpio.setup(21,0, nil,nil,0)--AGPIOWU1---3V3_EN
    gpio.set(21,1)
    log.info('打开GPS开关')


    libgnss.bind(gps_uart_id, uart.VUART_0)
    libgnss.on("raw", function(data)

        -- 默认不上报, 需要的话自行打开
        -- data = data:split("\r\n")
        -- if data == nil then
        --     return
        -- end

        -- for k, v in pairs(data) do
        --     if v and v:startsWith("$GNRMC") then
        --         sys.publish("mqtt_pub", "/gnss/" .. mobile.imei() .. "/up/nmea", v, 0)
        --     end
        -- end

    end)
    sys.wait(200) -- GPNSS芯片启动需要时间
   
    sys.wait(200) -- GPNSS芯片启动需要时间,大概150ms
    uart.write(gps_uart_id,_G.PositioningMode)
    sys.wait(20)
    uart.write(gps_uart_id, "$PCAS03,1,1,1,1,1,1,1,1,0,0,1,1,1*33\r\n") -- 默认所有name语句都打开
    sys.wait(20)
    
    
    while 1 do
        sys.wait(1000)

        -- 获取4G信号强度
        local rsrp=mobile.rsrp()
        _G.Mobile_Ss = rsrp+140 

        -- 获取GPS信号
        local Gsv=libgnss.getGsv()
        local Gsvv=json.encode(Gsv)
        local loc=libgnss.getRmc(1)
        locc=json.encode(loc)--其他文件要调用的量不要加local!!!
        libgnss.getIntLocation()
        local gga = libgnss.getGga(2)
        if gga then
            -- log.info("GGA------------------>", json.encode(gga, "11g"))
        end
        local gll = libgnss.getGll(2)
        if gll then
            -- log.info("GLL----------------->", json.encode(gll, "11g"))
        end

        -- GPS有效
        if loc.valid==true then
            Gps_Get_Num = 0

            local lat=loc.lat
            local lng=loc.lng
            local latt=lat/10000000--除法，保留小数--//除法，只保留整数
            local lngg=lng/10000000

            _G.old_latitude=json.encode(latt)
            _G.old_longitude =json.encode(lngg)
            _G.data_from="GPS"
            log.info("-------------------->> GPS定位成功！！！<<----------------------","lat------->",_G.old_latitude,"lng------->",_G.old_longitude)

            local total_sats=Gsv.total_sats
            local sats=Gsv.sats
            local snr=nil
            local LsnrNum=0

            for i=1,total_sats do
                snr=sats[i].snr
                if snr>25 then 
                    LsnrNum=LsnrNum+1
                end
            end
            
            _G.Gnss_Ss=LsnrNum
            _G.SatsNum=total_sats



        -- GPS数据无效
        elseif loc.valid==false then

            Gps_Get_Num=Gps_Get_Num+1
            log.info(Gps_Get_Num,"-------------------->>GPS定位失败<<----------------------原始数据:",locc) 

        end

        -- 数据大于等于十次后，LBS定位启动
        if Gps_Get_Num >= 10 then
            Gps_Get_Num = 0
            
            log.info("-------------------->>10次 GPS定位失败,改用基站定位!!!<<----------------------") 
            mobile.reqCellInfo(30)
            sys.wait(10000)
            mobile.getCellInfo()
            sys.waitUntil("CELL_INFO_UPDATE", 3000)
            lbsLoc.request(getLocCb) -- lbs进行普通定位
        end
        
    end
end)



-- 订阅GNSS状态编码
sys.subscribe("GNSS_STATE", function(event, ticks)
    -- event取值有 
    -- FIXED 定位成功
    -- LOSE  定位丢失
    -- ticks是事件发生的时间,一般可以忽略
    log.info("gnss", "state", event, ticks)
    if event == "FIXED" then
        local rmc = libgnss.getRmc(2)
        local locStr = { lat ,lng }
        locStr.lat = rmc.lat
        locStr.lng = rmc.lng
        local str = json.encode(locStr, "7f")
        io.writeFile("/gnssrmc", str)
        log.info("gnss", "rmc", str)
    end
end)



sys.taskInit(function()
    while 1 do
        sys.wait(3600*1000)
       
    end
end)

